package com.tjresearch.redisdbtasktracker.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.LineNumberReader;
import java.util.Properties;

import com.tjresearch.redisdbtasktracker.service.InsertDbService;


public class ReaderSqlUtils {
	
	private static final String PATHPROPERTIES = ReaderSqlUtils.class.getClassLoader().getResource(".").getPath()+"path.properties";
	private static String readpath = null;
	private static String markreadpath = null;
	static{
		Properties pros = new Properties();
		try {
			pros.load(new FileInputStream(PATHPROPERTIES));
			readpath = pros.getProperty("readpath");//读取sql文件的路径
			markreadpath = pros.getProperty("markreadpath");//读取后将sql文件放入的路径
			if(!new File(markreadpath).exists()){
				new File(markreadpath).mkdirs();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 逐行读取sql文件，将sql语句执行
	 * @param file
	 * @param insertDbService
	 * @throws Exception
	 */
	public static void Reader(File file,InsertDbService insertDbService) throws Exception{
		LineNumberReader lineNum = new LineNumberReader(new FileReader(file));
		String str = null;
		
		while ((str = lineNum.readLine()) != null){
			insertDbService.insertWithFile(str);
		}
		lineNum.close();
	}
	/**
	 * 读取所有sql文件
	 * @param insertDbService 
	 * @throws Exception
	 */
	public static void insertDb(InsertDbService insertDbService) throws Exception{
		File file = new File(readpath);
		File[] listFiles = file.listFiles();
		for (File f : listFiles) {//将该文件夹下的文件遍历然后读取,读取完就移到已读文件夹中
			if(f.isFile()){
				ReaderSqlUtils.Reader(f,insertDbService);
				f.renameTo(new File(markreadpath+f.getName()));
			}
		}
		
	}
	
	

}
